package com.autumn.security.auth.credential;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;

import com.autumn.security.auth.AutumnAuthenticationToken;
import com.autumn.security.auth.UserNamePasswordToken;
import com.autumn.security.crypto.IAutumnPasswordProvider;
import com.autumn.security.user.IAutumnUser;
import com.autumn.security.user.IAutumnUserCredentialsService;

/**
 * 密码匹配器
 * 
 * @author 杨昌国 2018-12-06 14:52:59
 */
public class AutumnCredentialsMatcher implements CredentialsMatcher {

	private final IAutumnPasswordProvider passwordProvider;
	private final IAutumnUserCredentialsService credentialsService;

	/**
	 * 
	 * @param passwordProvider
	 * @param credentialsService
	 */
	public AutumnCredentialsMatcher(IAutumnPasswordProvider passwordProvider,
			IAutumnUserCredentialsService credentialsService) {
		this.passwordProvider = passwordProvider;
		this.credentialsService = credentialsService;
	}

	@Override
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
		boolean result;
		IAutumnUser user = (IAutumnUser) info.getPrincipals().getPrimaryPrincipal();
		if (token instanceof UserNamePasswordToken) {
			UserNamePasswordToken userNamePasswordToken = (UserNamePasswordToken) token;
			String rawPassword = String.valueOf(userNamePasswordToken.getPassword());
			result = this.getPasswordProvider().matches(user, rawPassword);
		} else {
			result = true;
		}
		credentialsService.credentiaMatchResult((AutumnAuthenticationToken) token, user, result);
		return result;
	}

	/**
	 * 获取密码比较器
	 * 
	 * @return
	 */
	public IAutumnPasswordProvider getPasswordProvider() {
		return passwordProvider;
	}

	/**
	 * 获取认证服务
	 * 
	 * @return
	 */
	public IAutumnUserCredentialsService getCredentialsService() {
		return this.credentialsService;
	}
}
